﻿#ifdef WIN32
#include <Windows.h>
#endif
#include "web_class.h"
#include <QCoreApplication>
#include <QDesktopServices>
#include <QUrl>
#include <QDebug>
#include <QTextCodec>

#include <fstream>
#include <sstream>
#include <qapplication.h>
#include "main_widget.h"

#include "json.hpp"
#include <thread>
#include <qvector.h>

using namespace std;

enum class config_type {
    INT,
    BOOL,
    STRING
};

struct config_struct {
    config_struct(config_type t, QVariant default_value) :
    type(t),
    dvalue(default_value){

    }
    QVariant dvalue;
    config_type type;
};

std::map<QString, config_struct> config_map_ = {
  

    {"sys/smcAddress",{config_type::STRING,""}},
    {"sys/smcAccount",{config_type::STRING,""}},
    {"sys/smcPass",{config_type::STRING,""}},

    {"sys/adminAccount",{config_type::STRING,""}},
    {"sys/adminPass",{config_type::STRING,""}},

    {"sys/full_screen",{config_type::BOOL,false}},
    {"sys/powered_up",{config_type::BOOL,false}},

  

};





WebClass::WebClass(QObject* parent)
	:QObject(parent)
{

    main_widget_ = static_cast<MainWidget*>(parent);
  

    QString inipath = QCoreApplication::applicationDirPath() + "/conf/config.ini";

    setting_= make_shared<QSettings>(inipath, QSettings::IniFormat);
    setting_->setIniCodec(QTextCodec::codecForName("UTF-8"));
    init_get_all_config();

    meeting_service_ = new meet_service();
}

WebClass::~WebClass()
{
    qDebug() << "~WebClass";

}




void WebClass::save_config(const QString key, const QVariant& value)
{
    
        setting_->setValue(key, value); 

   
}

QVariant WebClass::get_config(const QString& key)
{
    auto iter = config_map_.find(key);
    if (iter != config_map_.end()) {
        return setting_->value(key, iter->second.dvalue);
    }
    return setting_->value(key);
}



void WebClass::init_get_all_config()
{
    QJsonObject RootObj;
    for (auto iter : config_map_)
    {
        if (iter.second.type == config_type::INT)
        {
            int v = setting_->value(iter.first, iter.second.dvalue).toInt();
            RootObj.insert(iter.first, v);

        }
        else if (iter.second.type == config_type::BOOL) {
            bool v = setting_->value(iter.first, iter.second.dvalue).toBool();
            RootObj.insert(iter.first, v);
        }
        else {
            
            QString v = setting_->value(iter.first, iter.second.dvalue).toString().toUtf8();
            RootObj.insert(iter.first, v);
        }
    }
    
    QJsonDocument Doc(RootObj);
    QByteArray strJson = Doc.toJson();
    all_config_= strJson;
}

QString WebClass::get_all_config()
{
    return all_config_;
}




void WebClass::drag_area_mouse_down()
{
#ifdef WIN32

    HWND hWnd = ::GetAncestor((HWND)(main_widget_->winId()), GA_ROOT);
    // get current mouse cursor position
    POINT pt;
    ::GetCursorPos(&pt);
    // in case the mouse is being captured, try to release it
    ::ReleaseCapture();
    // simulate that the mouse left button is down on the title area
    ::SendMessage(hWnd, WM_NCLBUTTONDOWN, HTCAPTION, POINTTOPOINTS(pt));
#endif // WIN32

}



#define AUTO_RUN "HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Run"

void WebClass::set_starting_up_auto_run(bool flag)
{

    QString appPath  = QApplication::applicationFilePath();
    QSettings settings(AUTO_RUN, QSettings::NativeFormat);

    //以程序名称作为注册表中的键,根据键获取对应的值（程序路径）
    QFileInfo fInfo(appPath);
    QString name = fInfo.baseName();    //键-名称

    //如果注册表中的路径和当前程序路径不一样，则表示没有设置自启动或本自启动程序已经更换了路径
    QString oldPath = settings.value(name).toString(); //获取目前的值-绝对路劲
    QString newPath = QDir::toNativeSeparators(appPath);    //toNativeSeparators函数将"/"替换为"\"
    if (flag)
    {
        if (oldPath != newPath)
            settings.setValue(name, newPath);
    }
    else
        settings.remove(name);
  
}

void WebClass::on_esc_pressed()
{

     if (main_widget_->is_full_)
         main_widget_->switch_full();
    
}

void WebClass::open_url(QString url)
{
    QDesktopServices::openUrl(QUrl(url));
}




QString WebClass::get_packge_files()
{
    QFileDialog dialog;
    QStringList fileList;
    dialog.setViewMode(QFileDialog::Detail); // 设置为多选
    dialog.setFileMode(QFileDialog::ExistingFiles); // 设置为多选
    dialog.setOption(QFileDialog::DontUseNativeDialog); // 使用Qt自己的对话框
    if (dialog.exec() == QDialog::Accepted) {
        fileList = dialog.selectedFiles(); // 返回选中的文件列表
    }

    json root;
    for (auto it : fileList)
    {
        json row;     
        QFileInfo fileInfo(it);
        row["name"] = fileInfo.fileName().toStdString();
        row["path"] = it.toStdString();
        root.push_back(row);
    }

    return QString::fromStdString(root.dump());
}


QString WebClass::terminal_update(QString data)
{
    json root = json::parse(data.toStdString());
    QNetworkAccessManager manager;



    QString terminalType = QString::fromStdString(root["terminalType"].get<string>());
    QString versionCode = QString::fromStdString(root["versionCode"].get<string>());
    QString versionName = QString::fromStdString(root["versionName"].get<string>());
    QString request_url = QString::fromStdString(root["request_url"].get<string>());

    // 创建一个 QHttpMultiPart 对象，用于组装 POST 请求的数据
    QHttpMultiPart* multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);



    QHttpPart namePart;
    namePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"versionName\""));
    namePart.setBody(versionName.toUtf8());
    multiPart->append(namePart);

    QHttpPart versionPart;
    versionPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"versionCode\""));
    versionPart.setBody(versionCode.toUtf8());
    multiPart->append(versionPart);


    QHttpPart typePart;
    typePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"terminalType\""));
    typePart.setBody(terminalType.toUtf8());
    multiPart->append(typePart);

    QHttpPart mustPart;
    mustPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"isMust\""));
    mustPart.setBody("1");
    multiPart->append(mustPart);

    // 添加文件到 QHttpPart 对象中

    QVector<QFile*> fileVec;

    for (auto it : root["fileList"])
    {

        QString filePath = QString::fromStdString(it["path"].get<string>());
        QString fileName = QString::fromStdString(it["name"].get<string>());
        QFile* file = new QFile(filePath);
        if (!file->open(QIODevice::ReadOnly)) {
            return "";
        }
        QHttpPart filePart;
        filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"fileList\"; filename=\"" + fileName + "\""));
        filePart.setBodyDevice(file);
        filePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/plain"));
        filePart.setHeader(QNetworkRequest::ContentLengthHeader, QVariant(file->size()));
        multiPart->append(filePart);
        fileVec.push_back(file);
    }


    // 创建 POST 请求
    //QUrl url("http://172.16.100.20:9488/tty/mobile/terminalUpgrade/upload");
    QUrl url(request_url);
    QNetworkRequest request(url);

    // 发送 POST 请求
    QNetworkReply* reply = manager.post(request, multiPart);

    QEventLoop eventLoop;
    connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
    eventLoop.exec(QEventLoop::ExcludeUserInputEvents);


    QByteArray replyData = reply->readAll();
    QNetworkReply::NetworkError Code = reply->error();
    QString Response = replyData;

    reply->deleteLater();
    multiPart->deleteLater();

    for (auto it : fileVec)
    {
        delete it;
    }

    return Response;
}


